<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item class="search-wrap-item" label="标题关键字：" prop="projectTitle">
        <el-input min-width="160px" placeholder="请输入标题关键字" v-model="searchFormData.projectTitle" clearable
          @keyup.enter="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="归属人：" prop="userName">
        <el-input min-width="360px" placeholder="请输入归属人" v-model="searchFormData.userName" clearable
          @keyup.enter="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker style="width: 240px" type="daterange" unlink-panels range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间" :value-on-clear="null" v-model="searchFormData.time" format="YYYY/MM/DD"
          value-format="YYYY-MM-DD" @change="getAllRequirements" />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="createRequirementClick">创建需求</el-button>
      </el-form-item> -->
    </el-form>

    <!-- [我负责的任务]列表区域 -->
    <div class="card-layout-box" id="cardLayoutBox">
      <div class="card-not-requirement" v-if="allRequirements.length === 0">暂无数据</div>
      <!-- 分类 -->
      <div v-if="allRequirements.length !== 0" class="card-box" v-for="(list, index) in allRequirements" :key="index">
        <!--        <div class="card-header-box" :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">-->
        <!--          {{ fatherStatus(list.status).text }} - {{ list.total }}-->
        <!--        </div>-->
        <div class="card-header-box">
          <el-tag :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">{{ fatherStatus(list.status).text
            }}</el-tag> - {{ list.total }}
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in list.requirements" :key="item.itemRequirementId"
              :class="{ 'red-bj': item.isOutTime === '是' }">
              <!-- 需求标题 -->
              <div class="card-list-left">
                <!-- 需求类别 -->
                <div class="card-list-type">
                  <span>
                    <el-icon :style="{ color: taskTypeContent(item.taskType).color }" :size="14">
                      <Flag />
                    </el-icon>
                    {{ taskTypeContent(item.taskType).text }}
                  </span>
                  <!--                    <span :style="{ color: taskTypeContent(item.taskType).color }">-->
                  <!--                      {{taskTypeContent(item.taskType).text }}-->
                  <!--                    </span>-->
                  <span>
                    <el-icon :style="{ color: isTsContent(item.isTs).color }" :size="15">
                      <Flag />
                    </el-icon>
                    {{ isTsContent(item.isTs).text }}
                  </span>
                  <!--                    <span :style="{ color: isTsContent(item.isTs).color }">-->
                  <!--                      {{ isTsContent(item.isTs).text }}-->
                  <!--                    </span>-->
                </div>
                <div class="card-header-title-box" @click="handleRowClick(item.itemRequirementId)"
                  :class="{ 'card-finished': item.requirementChildStatus === 9 }">
                  <b>
                    {{ item.itemRequirementName }}
                  </b>
                </div>
                <!-- 任务附加信息 -->
                <div class="card-list">
                  <!-- <div class="card-small"> -->
                  <!-- <div class="card-list-small-item boss-name" v-if="item.requirementAuditName">审核人：{{
                    item.requirementAuditName }}</div> -->
                  <!-- <div class="card-list-small-item boss-name" v-if="item.requirementBossName">技术负责人：{{
                    item.requirementBossName == "" ? "无" :
                      item.requirementBossName }}</div> -->
                  <!-- <div class="card-list-small-item boss-name" v-if="item.avgUserName">技术负责人：{{
                    item.avgUserName == "" ? "无" :
                      item.avgUserName }}</div> -->
                  <!-- <div class="card-list-small-item test-list" v-if="item.requirementRelevances">参与人：{{ item.requirementRelevances }}</div> -->
                  <div class="card-list-small-item test-list" v-if="item.userName">归属人：{{ item.userName }}</div>
                  <!-- 测试中状态 -->
                  <div class="card-list-small-item test-list"
                    :style="{ color: testStatus(item.submitTestNext)?.bgColor }"
                    v-if="(item.requirementChildStatus == 5 && item.taskType !== 3)">
                    {{ testStatus(item.submitTestNext)?.text }}</div>
                  <!-- </div> -->
                </div>
                <!-- 任务时间 -->
                <div class="card-list-small-item begin-time">
                  <el-icon>
                    <Clock style="position: absolute;left: 0;top:2px;" />
                  </el-icon>
                  {{ tableTimeDate(item.guessTime8) }} - <span :class="{ 'red-text': item.isOutTime === '是' }">{{
                    tableTimeDate(item.guessTime) }}</span>
                </div>
                <!-- 延期图标 -->
                <div class="icon-img" v-if="item.isOutTime === '是'">
                  <img src="../../../assets/images/icon-delay.png" style="width: 50px;" />
                </div>
              </div>

              <!-- 研发人员-上线任务操作 -->
              <!-- <div class="operate-box"
                v-if="item.requirementChildStatus < 6 && !isTestId && item.requirementChildStatus !== 4 && item.requirementChildStatus !== 1 && (item.taskType == 1 || item.taskType == 0) && item.isTs === 1">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#2d8cf0"><MoreFilled /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu> -->
              <!-- 提测需求前要先上传详细设计 -->
              <!-- <el-dropdown-item v-if="item.requirementChildStatus == 3"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ item.itemRequirementWorldDetailed == "" ? "上传详细设计" : item.isGetTest == 1 ? '评分' :
                          fatherStatus(item.requirementChildStatus).operate }}
                      </el-dropdown-item> -->

              <!-- 已上传详细设计，未提测 -->
              <!-- <el-dropdown-item
                        v-if="item.requirementChildStatus !== 9 && item.requirementChildStatus < 4 && item.requirementChildStatus !== 3"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ fatherStatus(item.requirementChildStatus).operate }}
                      </el-dropdown-item> -->

              <!-- 重新提测 -->
              <!-- <el-dropdown-item v-if="!isTestId && item.requirementChildStatus == 5"
                        :disabled="item.submitTestNext == 5 ? false : true"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        重新提测
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
</el-dropdown>
</div> -->

              <!-- <div class="operate-box"
                v-if="item.requirementChildStatus === 5 && !isTestId && (item.taskType == 1 || item.taskType == 0) && item.isTs === 3">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#2d8cf0"><MoreFilled /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                       <el-dropdown-item
                          :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                          {{ item.isUploadCase == 1 ? "上传用例" : "测试结果" }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div> -->

              <!-- 测试人员-上线任务操作 -->
              <!-- <div class="operate-box"
                v-if="(userAuthId == '111' || userAuthId == '666') && item.requirementChildStatus == 5 && (item.taskType == 1 || item.taskType == 0)">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#409EFF"><MoreFilled /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ item.isUploadCase == 1 ? "上传用例" : "测试结果" }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div> -->

              <!-- 运维、回归、日常任务操作: taskType=2、3、4 -->
              <div class="operate-box"
                v-if="((item.taskType !== 1 && item.taskType !== 0) && (item.requirementChildStatus !== 9 && item.requirementChildStatus !== 8))">
                <el-dropdown
                  v-if="(item.taskType !== 3 && (item.isTs !== 1 || item.isTs !== 2)) || (item.taskType == 3 && ((item.isTs == 3 && item.requirementChildStatus == 5)))"
                  :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#409EFF">
                      <MoreFilled />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ (item.isUploadCase == 1 && item.taskType == 3 && item.requirementChildStatus == 5) ? "上传用例" :
                          "完成" }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>


              <!-- 上线-研发任务：taskType=1，isTs=1 -->
              <div class="operate-box"
                v-if="item.taskType == 1 && item.isTs == 1 && item.requirementChildStatus !== 4 && item.requirementChildStatus < 6">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#2d8cf0">
                      <MoreFilled />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- 提测需求前要先上传详细设计 -->
                      <el-dropdown-item v-if="item.requirementChildStatus == 3"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ item.itemRequirementWorldDetailed == "" ? "上传详细设计" : item.isGetTest == 1 ? '评分' :
                          fatherStatus(item.requirementChildStatus).operate }}
                      </el-dropdown-item>

                      <!-- 已上传详细设计，未提测 -->
                      <el-dropdown-item
                        v-if="item.requirementChildStatus !== 9 && item.requirementChildStatus < 4 && item.requirementChildStatus !== 3"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ fatherStatus(item.requirementChildStatus).operate }}
                      </el-dropdown-item>

                      <!-- 重新提测 -->
                      <el-dropdown-item v-if="item.requirementChildStatus == 5"
                        :disabled="item.submitTestNext == 5 ? false : true"
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        重新提测
                      </el-dropdown-item>

                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>

              <!-- 上线-测试任务：taskType=1，isTs=3 -->
              <div class="operate-box" v-if="item.taskType == 1 && item.isTs == 3 && item.requirementChildStatus == 5">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#2d8cf0">
                      <MoreFilled />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        :command="{ requirement: item, operate: fatherStatus(item.requirementChildStatus).status }">
                        {{ item.isUploadCase == 1 ? "上传用例" : "测试结果" }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>


            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 待开发->开发中：需求评审会议纪要 -->
    <el-dialog style="min-height: 540px;" :close-on-click-modal="false" v-model="dialogReviewMeetVisible" title="状态变更"
      @close="handleCloseDiglog" @closed="handleCloseDiglog">
      <el-form>
        <el-form-item label="需求评审会议纪要：">
          <el-input style="max-height: 500px; overflow-y: auto;" :autosize="{ minRows: 20, maxRows: 20 }"
            placeholder="请输入会议纪要..." type="textarea" v-model="reviewMeetingMsg" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCloseDiglog">取消</el-button>
          <el-button type="primary" @click="handleDeveloping">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开发中-上传详细设计，提测分支 -->
    <!-- 提测前上传详细设计 -->
    <el-dialog class="dialog-container" style="
        min-height: 400px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
      " :close-on-click-modal="false" v-model="dialogDesignFileVisible" title="请上传详细设计" @close="handleCloseDiglog"
      @closed="handleCloseDiglog">
      <el-button style="margin-bottom: 10px;" type="primary" size="small" plain
        @click="openModal = true">关联文件</el-button>

      <!-- <el-upload class="upload-demo" action="" multiple="true" v-model:file-list="fileText" :http-request="handleUpLoad"
        :on-success="handleSuccess" :on-error="handleError" :on-remove="handleRemove">
        <el-button class="upload-btn" type="primary" plain size="small">上传文件</el-button>
      </el-upload> -->

      <UploadFilesVue :initConfig="initConfig" @updateFilePaths="handleUpdateFilePaths" :resetFiles="resetFiles"></UploadFilesVue>


      <!-- 关联的文件 -->
      <div
        style="margin-top: 10px;width: 100%;height: 500px; display: flex;flex-direction: column;flex-wrap: nowrap; overflow-y: auto;">
        <el-tag style="margin-bottom: 5px;display: flex;justify-content: space-between;margin-right: 10px;"
          v-for="(file, index) in newAssFilesList" :key="index" closable :disable-transitions="false"
          @close="handleDelAssFile(file)">
          {{ handleFileName(file).fileName }}
        </el-tag>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCloseDiglog">取消</el-button>
          <el-button type="primary" @click="handleDesignFile(isRequirementData.ID)">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 首次提交提测分支 -->
    <el-dialog class="dialog-container" style="
        max-height: 670px;
        display: flex;
        flex-direction: column;
      " :close-on-click-modal="false" v-model="dialogTestVisible" title="操作" @close="handleCloseTestDialog"
      @closed="handleCloseTestDialog">
      <el-form class="dialog-test-form" label-position="right" label-width="180px" ref="testFormRef"
        :rules="testFormRules" :model="testFormData">
        <el-form-item v-if="isRequirementData.isGetTest != 1" label="是否涉及代码改动：">
          <el-switch v-model="isChangeData" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="选择测试：" v-if="isRequirementData.isGetTest != 1" prop="ts">
          <template #="defalut">
            <el-select v-model="testFormData.ts" multiple v-if="testOptions.length > 0" placeholder="请选择测试人员"
              :required="isChangeData">
              <el-option v-for="item in testOptions" :key="item.uuid" :label="item.nickName" :value="item.uuid" />
            </el-select>
            <p style="color: red" v-if="testOptions.length == 0">暂未分配测试，请先通知测试负责人分配测试人员</p>
          </template>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest != 1" label="提测产品分支：" :required="isChangeData"
          prop="pullBranch1">
          <el-input v-model="testFormData.pullBranch1" placeholder="请输入产品分支"></el-input>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest != 1" label="提测项目分支：" :required="isChangeData"
          prop="pullBranch2">
          <el-input v-model="testFormData.pullBranch2" placeholder="请输入项目分支"></el-input>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest != 1" label="提测内容说明：" required prop="submitTest">
          <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" v-model="testFormData.submitTest"
            placeholder="请简述提测内容...">
          </el-input>
        </el-form-item>
        <el-form-item label="对【技术负责人】评分：" required prop="itemRequirementYTOYNumber">
          <el-input-number v-model="testFormData.itemRequirementYTOYNumber" controls-position="right" min="0" max="100" />
          （备注：评分分值：1-100；概要设计文档是否清晰明了，分配合理，有协助，攻克难点，协助指导等...）
        </el-form-item>
        <el-form-item label="对【技术负责人】评语：" required prop="itemRequirementYTOYTip">
          <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" v-model="testFormData.itemRequirementYTOYTip"
            placeholder="请输入对【技术负责人】工作情况评语；备注：不需要回答是否，不符合以下4点问题，对【技术负责人】评分自动扣1题25分；（1、概要设计文档是否清晰明了？2、分配任务是否明确无歧义？3、是否有协助，攻克难点？4、提测后，是否有协助查看详细设计文档，完成代码审核，给出指导意见？）">
          </el-input>
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="defalut" @click="handleCloseTestDialog">取消</el-button>
            <el-button type="primary"
              :disabled="testOptions.length == 0 && isRequirementData.itemRequirementIsGetTest == 2"
              @click="submitTestData(testFormRef)">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 测试前必须先上传测试用例 -->
    <el-dialog width="1400px" style="min-height: 600px;margin-top: 8vh" v-model="dialogTestCaseVisible" title="添加测试用例"
      :close-on-click-modal="false">
      <TestRequirementCaseVue :visible="dialogTestCaseVisible" :testCaseSearch="testCaseSearch" :isOperation="1"
        :isAllCase="false" @add-success="handleAddSuccess"></TestRequirementCaseVue>
    </el-dialog>

    <!-- taskType:1-测试不通过-重新提测 -->
    <el-dialog v-model="dialogAgainTestVisible" title="重新提测" :close-on-click-modal="false"
      @close="handleCloseTestDialog" @closed="handleCloseTestDialog">
      <el-form label-position="right" label-width="120px" ref="againTestFormRef" :rules="againTestFormRules"
        :model="againTestFormData">
        <el-form-item label="选择测试：" prop="childChildId">
          <el-select style="width: 240px" v-model="againTestFormData.childChildId" filterable clearable
            placeholder="请选择测试人员">
            <el-option v-for="item in againTestOptions" :key="item.ID" :label="item.testName" :value="item.ID"
              :disabled="item.testStatus < 5" />
          </el-select>
        </el-form-item>
        <el-form-item label="提测产品分支：" prop="pullBranch1">
          <el-input v-model="againTestFormData.pullBranch1" placeholder="请输入产品分支"></el-input>
        </el-form-item>
        <el-form-item label="提测项目分支：" prop="pullBranch2">
          <el-input v-model="againTestFormData.pullBranch2" placeholder="请输入项目分支"></el-input>
        </el-form-item>
        <el-form-item label="提测内容说明：" prop="submitTest">
          <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" v-model="againTestFormData.submitTest"
            placeholder="请简述提测内容...">
          </el-input>
        </el-form-item>
        <el-form-item>
          <div class="dialog-form-footer">
            <el-button type="primary" @click="handleCloseAgainTestDialog">取消</el-button>
            <el-button type="primary" @click="submitAgainTestData(againTestFormRef)">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- taskType:1-测试通过操作弹窗 -->
    <el-dialog v-model="dialogTestResultVisible" title="测试结果" :close-on-click-modal="false"
      @close="handleCloseTestScoresDialog" @closed="handleCloseTestScoresDialog" v-loading="submitLoading">
      <!-- 测试负责人创建的需求-对测试负责人评论评分 -->
      <div
        v-if="isRequirementData.isGetTest == 1 || isRequirementData.requirementBossName == '刘涛' || isRequirementData.requirementBossName == '胡文斌'">
        <el-form ref="testToTestFormRef" :rules="testToTestFormRules" :model="testToTestFormData">
          <el-form-item style="width: 100%;">
            <div style="text-align: center;">
              <el-icon color="red" :size="16">
                <WarningFilled />
              </el-icon>
              <span style="font-weight: bold;">{{ isRequirementData.requirementName }}，</span>
              是否确认测试通过？
              <span style="color: red;">若确认将立即关闭该需求！</span>
            </div>
          </el-form-item>

          <el-form-item label="对测试负责人的评语：" required prop="testToTestBossTip" label-width="170px">
            <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea"
              v-model="testToTestFormData.testToTestBossTip" placeholder="请写下对测试的评语">
            </el-input>
          </el-form-item>
          <el-form-item label="对测试负责人评分：" prop="testToTestBossTipNumber" label-width="170px">
            <el-input-number v-model="testToTestFormData.testToTestBossTipNumber" controls-position="right" min="0" max="100" />
          </el-form-item>
          <el-form-item>
            <div class="dialog-form-footer">
              <el-button @click="handleCloseTestScoresDialog">取消</el-button>
              <el-button type="primary" @click="handleUpdateSubmitNotTip(testToTestFormRef)">通过</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 非测试负责人创建的需求且需要测试参与 -->
      <div
        v-if="isRequirementData.isGetTest !== 1 && (isRequirementData.requirementBossName !== '刘涛' || isRequirementData.requirementBossName !== '胡文斌')">
        <div style="display: flex; flex-direction: row;justify-content: space-between;">
          <div>
            <span>测试是否通过：</span>
            <el-switch v-model="isTestResult" inline-prompt active-text=" 通过 " inactive-text="不通过" :size="'large'"
              @change="handleChangeIsTestResult" />
          </div>
          <div v-if="!isTestResult">
            <el-button type="primary" size="small" @click="handleOpenAddBug(isRequirementID)">添加Bug</el-button>
          </div>
        </div>
        <!-- 测试通过表单 -->
        <el-form label-position="left" label-width="120px" v-if="isTestResult" ref="showTipCTOYRef"
          :rules="showTipCTOYRules" :model="showTipCTOYForm">
          <el-form-item label="请选择提测人：" prop="childChildIdId" label-width="120px">
            <el-select v-model="showTipCTOYForm.childChildIdId" placeholder="请选择提测人" style="width: 240px" clearable
              filterable>
              <el-option v-for="item in allTestUserList" :key="item.ID" :label="item.submitTestName" :value="item.ID"
                :disabled="item.testStatus == 4 || item.testStatus == 1 || item.testStatus == 5" />
            </el-select>
          </el-form-item>
          <el-form-item label="对研发评分：" prop="itemRequirementCTOYNumber" label-width="120px">
            <el-input-number v-model="showTipCTOYForm.itemRequirementCTOYNumber" controls-position="right" min="0" max="100" />
            （备注：评分分值：1-100；详细设计文档是否清晰明了，Bug修复是否及时，Bug数量是否过多，沟通态度是否友好等...）
          </el-form-item>
          <el-form-item label="对研发评语：" prop="itemRequirementCTOYTip" label-width="120px">
            <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea"
              v-model="showTipCTOYForm.itemRequirementCTOYTip"
              placeholder="请输入对【研发】工作情况评语；备注：不需要回答是否，不符合以下4点问题，对【研发】评分自动扣1题25分；（1、详细设计是否完整，阐述清楚？2、Bug修复是否及时？3、Bug数量是否过多？4、沟通态度是否友好？）">
            </el-input>
          </el-form-item>
          <el-form-item label="对测试负责人的评分：" prop="testToTestBossTipNumber" label-width="170px">
            <el-input-number v-model="showTipCTOYForm.testToTestBossTipNumber" controls-position="right" min="0" max="100" />
          </el-form-item>
          <el-form-item label="对测试负责人的评语：" prop="testToTestBossTip" label-width="170px">
            <el-input :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" v-model="showTipCTOYForm.testToTestBossTip"
              placeholder="请输入对测试负责人工作情况评语；）">
            </el-input>
          </el-form-item>

          <el-form-item>
            <div class="dialog-form-footer">
              <el-button @click="handleCloseTestScoresDialog">取消</el-button>
              <el-button type="primary" @click="submitScoreData(showTipCTOYRef)">通过</el-button>
            </div>
          </el-form-item>
        </el-form>


        <!-- 测试不通过表单 -->
        <el-form label-position="left" label-width="140px" v-if="!isTestResult" ref="testFaliedBugRef"
          :rules="testFaliedBugRules" :model="testFaliedBugForm">
          <el-form-item label="请选择提测人：" prop="childChildId" label-width="120px">
            <el-select v-model="testFaliedBugForm.childChildId" placeholder="请选择提测人" style="width: 240px" clearable
              filterable>
              <el-option v-for="item in allTestUserList" :key="item.ID" :label="item.submitTestName" :value="item.ID"
                :disabled="item.testStatus == 4 || item.testStatus == 1 || item.testStatus == 5" />
            </el-select>
          </el-form-item>

          <el-form-item label="选择测试Bug：" prop="bugIds" label-width="120px">
            <p v-if="allBugList.length == 0">暂无Bug，请<span style="color: #409EFF;cursor: pointer;"
                @click="handleOpenAddBug(isRequirementID)">先添加Bug</span></p>
            <!-- bug列表不为空 -->
            <div style="width: 100%;display: flex; flex-direction: row; align-content: center;">
              <el-transfer v-if="allBugList.length !== 0" v-model="testFaliedBugForm.bugIds" :data="allBugList"
                filterable filter-placeholder="搜索" :titles="['未选中', '已选中']" />
            </div>
          </el-form-item>
          <el-form-item>
            <div class="dialog-form-footer">
              <el-button @click="handleCloseTestScoresDialog">取消</el-button>
              <el-button type="primary" @click="handleTestFalied(testFaliedBugRef)">不通过</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- taskType:2、3、4-完成操作 -->
    <el-dialog style="width: 1200px;max-height: 800px;" v-model="dialogTaskResultVisible" title="任务完成">
      <el-form style="max-height: 600px; overflow-y: auto" ref="testSuccessFormRef" :model="testSuccessFormData"
        :rules="testSuccessFormRules" label-width="160">
        <el-form-item label="任务内容：">
          <el-input type="text" v-model="isRequirementData.processJob" disabled></el-input>
        </el-form-item>
        <el-form-item prop="taskMsg" label="任务完成描述：" required>
          <EditorMsgVue :modelValue="testSuccessFormData.taskMsg" @update:modelValue="updateMsg"></EditorMsgVue>
        </el-form-item>
        <el-form-item prop="taskWorldUrls" label="任务完成文件："
          :required="(isRequirementData.taskType == 3 && isRequirementData.isTs == 2)">
          <!-- <el-upload v-model:file-list="fileText" class="upload-demo" action="" size="small"
            :http-request="handleUpLoad" :on-success="handleSuccess" :on-error="handleError" :on-remove="handleRemove">
            <el-button type="primary">上传文件</el-button>
          </el-upload> -->

          <div style="width: 100%;">
            <el-button type="primary" size="small" plain @click="openModal = true">
                关联
            </el-button>
            <UploadFilesVue :initConfig="initConfig" @updateFilePaths="handleUpdateFilePaths" :resetFiles="resetFiles"></UploadFilesVue>
          </div>

          <!-- 关联的文件 -->
          <div style="margin-top: 10px;width: 100%;display: flex;flex-direction: column;flex-wrap: wrap;">
            <el-tag
              style="margin-bottom: 5px;display: flex;justify-content: space-between;margin-right: 10px;"
              v-for="(file, index) in newAssFilesList"
              :key="index"
              closable
              :disable-transitions="false"
              @close="handleDelAssFile(file)"
            >
              {{ handleFileName(file).fileName }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item v-if="isRequirementData.taskType == 3 && isRequirementData.isTs == 3" label="已测试通过用例：" required>
          <el-table ref="itemTestCaseRef" max-height="300px" stripe :data="requirementCaseList" row-key="ID"
            highlight-current-row @selection-change="handleSelectionChange">
            <el-table-column type="selection" fixed :selectable="selectable" width="30"
              align="center"></el-table-column>
            <el-table-column type="expand" fixed width="30">
              <template #default="props">
                <el-descriptions class="margin-top" title="用例详情：" :column="6" size="small">
                  <el-descriptions-item label="项目名称：" :span="1">{{ props.row.pname }}</el-descriptions-item>
                  <el-descriptions-item label="用例名称：" align="left" :span="4">{{
                    props.row.testCaseName }}</el-descriptions-item>
                  <el-descriptions-item label="用例编写人：" :span="1">{{ props.row.caseEditMembers }}</el-descriptions-item>

                  <el-descriptions-item label="项目分支名称：" :span="2">{{ props.row.pNameBranch }}</el-descriptions-item>
                  <el-descriptions-item label="功能模块：" :span="2">{{ props.row.funcModules }}</el-descriptions-item>
                  <el-descriptions-item label="二级功能模块：" :span="2">{{ props.row.funcModulesChild
                    }}</el-descriptions-item>

                  <el-descriptions-item label="前置条件：" :span="3">{{ props.row.beforeConditions }}</el-descriptions-item>
                  <el-descriptions-item label="用例优先级：" :span="3">{{ props.row.testCasePriority }}</el-descriptions-item>

                  <el-descriptions-item label="操作步骤：" :span="6">
                    <el-input v-if="props.row.operationSteps" type="textarea" v-model="props.row.operationSteps"
                      disabled :autosize="true"></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item label="预期结果：" :span="6">
                    <el-input v-if="props.row.expectedResult" type="textarea" v-model="props.row.expectedResult"
                      disabled :autosize="true"></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item label="实际结果：" :span="6">
                    <el-input v-if="props.row.realResult" type="textarea" v-model="props.row.realResult" disabled
                      :autosize="true"></el-input>
                  </el-descriptions-item>

                  <el-descriptions-item label="备注：" :span="6">
                    <el-input v-if="props.row.testCaseRemarks" type="textarea" v-model="props.row.testCaseRemarks"
                      disabled :autosize="true"></el-input>
                  </el-descriptions-item>
                </el-descriptions>
              </template>
            </el-table-column>
            <!-- <el-table-column type="index" label="序号" width="60" align="center" sortable></el-table-column> -->
            <el-table-column label="用例名称" min-width="240" align="left">
              <template #="{ row }">
                <el-text :style="{ color: row.testCaseName ? '#606266' : '#ccc' }">{{ row.testCaseName ?
                  row.testCaseName :
                  '—' }}</el-text>
              </template>
            </el-table-column>
            <el-table-column label="项目分支" min-width="160" align="center">
              <template #="{ row }">
                <el-text :style="{ color: row.pNameBranch ? '#606266' : '#ccc' }">{{ row.pNameBranch ? row.pNameBranch :
                  '—'
                  }}</el-text>
              </template>
            </el-table-column>
            <!-- <el-table-column label="功能模块" width="240" align="center">
              <template #="{ row }">
                <el-text :style="{ color: row.funcModules ? '#606266' : '#ccc' }">{{ row.funcModules ? row.funcModules : '—'
                  }}</el-text>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="二级功能模块" min-width="240" align="center">
              <template #="{ row }">
                <el-text :style="{ color: row.funcModulesChild ? '#606266' : '#ccc' }">{{ row.funcModulesChild ?
                  row.funcModulesChild : '—' }}</el-text>
              </template>
            </el-table-column> -->
            <el-table-column label="优先级" width="160" align="center" show-overflow-tooltip>
              <template #="{ row }">
                <el-text :style="{ color: row.testCasePriority ? '#606266' : '#ccc' }">{{ row.testCasePriority ?
                  row.testCasePriority : '—' }}</el-text>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <div class="dialog-form-footer">
            <el-button type="defalut" @click="handleCloseTestSuccessDialog">取消</el-button>
            <el-button type="primary" @click="submitTestSuccessData(testSuccessFormRef)">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible"
      @close="handleCloseDiglog" @closed="handleCloseDiglog" top="8vh">
      <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="true">
      </CommonRequirementInfoVue>
    </el-dialog>

    <!-- 开启添加Bug弹窗 -->
    <el-dialog v-if="dialogAddBugVisible" style="width: 1250px; margin-top: 5vh;" title="添加Bug"
      :close-on-click-modal="false" v-model="dialogAddBugVisible" @close="dialogAddBugVisible = false"
      @closed="dialogAddBugVisible = false">
      <AddRequirementBugVue :visible="dialogAddBugVisible" :id="isRequirementID" @submit-success="handleSubmitSuccess">
      </AddRequirementBugVue>
    </el-dialog>

    <!-- 关联文件 -->
    <AssRequiremenFileVue v-model:isOpen="openModal" @add-files="handleAddFiles"></AssRequiremenFileVue>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ElForm } from "element-plus";
import {
  getNewFatherRequirementStatus,
  postPVPRequirement,
  PutShowNeedTip,
  PostSubmitTestStatus,
  GetJoinTests,
  postSubmitTestRequirement,
  GetUpdateSubmitNotTips,
  PutShowTipCTOY,
  GetRequirementsBugs,
  GetSubmitRequirementList,
  GetMySubmitByRequirementChild,
  PostSubmitTestRequirementTwo,
  PutTestToBossTip,
  postNewPVPRequirement,
  TaskRequirementSuccess,
  GetChildTestCaseList,
} from "@/api/newDemands/index";
import { postUploadFile } from "@/api/common/index";
import { handleUploadRequirement } from "@/utils/common";
import { tableTimeDate, fatherStatus, isUserAuthId, isValidateString, testStatus, taskTypeContent, isTsContent, isValidateEditor, handleFileName, } from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import AddRequirementBugVue from "@/components/requirement/addRequirementBug.vue";
import TestRequirementCaseVue from "@/components/requirement/testRequirementCase.vue";
import EditorMsgVue from "@/components/requirement/editorMsg.vue";
import AssRequiremenFileVue from '@/components/requirement/assRequiremenFile.vue';
import UploadFilesVue from "@/components/requirement/uploadFiles.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const submitLoading = ref(false);
const userAuthId = ref<any>(null);//当前用户权限id
const isTestId = ref<any>(null);//是否为测试人员
const allRequirements = ref<any>([]); // 我所有的研发任务
const searchFormData = ref({
  projectTitle: "",
  userName: "",
  time: [null, null]
});

const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogDesignFileVisible = ref(false);//控制上传详细设计弹窗控件
const dialogTestVisible = ref(false);//控制提测弹窗控件
const dialogReviewMeetVisible = ref(false);//控制需求评审会议纪要弹窗
const dialogUploadCasesVisible = ref(false);//控制上传测试弹窗控件
const isChangeData = ref(true);//控制是否涉及代码改动滑块
const isUploadCases = ref(true);//控制是否上传测试用例滑块
const dialogTestResultVisible = ref(false);//控制测试是否通过弹窗控件
const dialogAgainTestVisible = ref(false);//控制重新提测弹窗控件
const dialogAddBugVisible = ref(false);// 控制开启添加bug弹窗控件
const dialogTestCaseVisible = ref(false);// 控制开启上传测试用例弹窗
const dialogTaskResultVisible = ref(false);// 控制任务完成弹窗


const isRequirementID = ref(); //当前操作任务ID
const isRequirementData = ref<any>(null);//当前需求数据
const fileText = ref([]);//概要设计文件显示
const filePath = ref<any>([]);//概要设计文件地址
const reviewMeetingMsg = ref("");//需求评审会议纪要内容
const testFormRef = ref<FormInstance>();//提测表单实例
const testOptions = ref<any>([]);//提测测试人员列表
const testCaseSearch = ref<any>({
  itemItemId: null,
  childId: null,
  isUploadCase: null,
  fatherId: null
}); // 测试用例组件传参
// const checkTests = ref<any>([]);//选中提测测试
// const testScoreRef = ref<FormInstance>();//测试对研发评论表单实例
// TODO 关联文件
const openModal = ref(false);
const newAssFilesList = ref<any>([]);// 新关联的文件
const filePaths = ref<any>("");//详细设计文件

//* 上传文件初始配置
const initConfig = ref({
  tipText: "",// 提示文本
  type: "primary",// 按钮类型
  plain: true,// 按钮样式
  btnText: "上传文件",// 按钮文本
  fileUrl: "/file/upload_file",// 上传地址
  fileType: "detailedPath",// 上传类型
  fileTypeId: "5",// 上传类型id
});
const resetFiles = ref(false);// 是否清除已上传文件列表


const testFormData = ref<any>({
  childId: null,
  ts: [],
  pullBranch1: "",
  pullBranch2: "",
  submitTest: "",
  itemRequirementYTOYTip: "",
  itemRequirementYTOYNumber: 100

});//提测数据


// 自定义不能为空值的校验规则
const pullBranch1Validator = (rule: any, value: any, callback: any) => {
  if (isChangeData.value) {
    if (value.trim() == "") {
      return callback(new Error("必填，且不能为空"));
    };
  }
  callback();
};
const commonValidator = (rule: any, value: any, callback: any) => {
  if (value.trim() == "") {
    return callback(new Error("必填，且不能为空"));
  };
  callback();
};

const testFormRules = reactive<FormRules<any>>({
  ts: [
    { required: isChangeData.value, message: "必填", trigger: "blur" }
  ],
  pullBranch1: [
    { required: isChangeData.value, message: "必填", trigger: "blur" },
    { required: isChangeData.value, validator: pullBranch1Validator, trigger: "blur" }
  ],
  pullBranch2: [
    { required: true, message: "必填", trigger: "blur" },
    { required: isChangeData.value, validator: pullBranch1Validator, trigger: "blur" }
  ],
  submitTest: [
    { required: true, message: "必填", trigger: "blur" },
    { required: isChangeData.value, validator: pullBranch1Validator, trigger: "blur" }
  ],
  itemRequirementYTOYTip: [
    { required: true, message: "必填", trigger: "blur" },
    { validator: commonValidator, trigger: "blur" }
  ],
  itemRequirementYTOYNumber: [{ required: true, message: "必填", trigger: "blur" }],
});//提测数据校验规则


/* 测试中 */
// TODO 研发参与的测试任务
const isTestResult = ref(true);// 控制测试是否通过;
//* 测试通过-对研发评论
const showTipCTOYRef = ref<FormInstance>();//测试通过表单实例
// 测试通过-对研发评论的表单校验规则
const showTipCTOYRules = reactive({
  childChildIdId: [{ required: true, message: "必填", trigger: "blur", }],
  itemRequirementCTOYTip: [
    {
      required: true,
      message: "必填",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    },
  ],
  itemRequirementCTOYNumber: [{ required: true, message: "必填", trigger: "blur", }],
  testToTestBossTip: [
    {
      required: true,
      message: "必填",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    },
  ],
  testToTestBossTipNumber: [{ required: true, message: "必填", trigger: "blur", }],
});
// 测试通过-对研发评论表单数据
const showTipCTOYForm = ref<any>({
  childChildIdId: null,
  itemRequirementCTOYTip: "",
  itemRequirementCTOYNumber: 100,
  childId: null,
  testToTestBossTip: "",
  testToTestBossTipNumber: 100,
});

//* 测试不通过-提交bug列表
const allBugList = ref<any>([]);// 根据需求id获取到的所有bug
const allTestUserList = ref<any>([]);// 根据需求id获取给自己提测的研发人员名单
const testFaliedBugRef = ref<FormInstance>();// 测试不通过时的表单实例
// 测试通过-对研发评论的表单校验规则
const testFaliedBugRules = reactive({
  childChildId: [{ required: true, message: "必填", trigger: "blur", }],
  bugIds: [{
    required: true,
    message: "必选",
    trigger: "blur",
    validator: (rule: any, value: any, callback: any) => {
      // 调用自定义验证函数
      if (value.length == 0) {
        callback(new Error("请添加提测bug!"));
      } else {
        callback();
      }
    }
  }],
});
const testFaliedBugForm = ref<any>({
  childChildId: null,
  bugIds: []
});

// * 测试不通过-研发重新提测
const againTestOptions = ref<any>([]);// 重新提测的测试人员列表
const againTestFormRef = ref<FormInstance>();// 重新提测表单实例
const againTestFormRules = reactive({
  childChildId: [
    { required: true, message: "必填", trigger: "blur" },
  ],
  pullBranch1: [
    { required: true, message: "必填", trigger: "blur" },
    { required: true, validator: pullBranch1Validator, trigger: "blur" }
  ],
  pullBranch2: [
    { required: true, message: "必填", trigger: "blur" },
    { required: true, validator: pullBranch1Validator, trigger: "blur" }
  ],
  submitTest: [
    { required: true, message: "必填", trigger: "blur" },
    { validator: pullBranch1Validator, trigger: "blur" }
  ],
});// 重新提测表单校验规则
const againTestFormData = ref<any>({
  childChildId: null,
  pullBranch1: "",
  pullBranch2: "",
  submitTest: "",
  ts: [{
    userName: "",
    uuid: ""
  }]
});// 重新提测表单数据

// TODO 测试对测试负责人评价
const testToTestFormRef = ref<FormInstance>();
const testToTestFormRules = reactive({
  testToTestBossTip: [
    {
      required: true,
      message: "必填",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    },
  ],
  testToTestBossTipNumber: [{ required: true, message: "必填", trigger: "blur", }],
});
const testToTestFormData = ref<any>({
  childId: null,
  testToTestBossTip: "",
  testToTestBossTipNumber: 100
});


// TODO 任务完成提交数据
const testSuccessFormRef = ref<FormInstance>();
const testSuccessFormRules = reactive({
  taskMsg: {
    required: true,
    message: "必填",
    trigger: "blur",
    validator: (rules: any, value: any, callback: any) => {
      if (isValidateEditor(value)) {
        callback(new Error("必填，且不能为空格或空行！"));
      } else {
        callback();
      }
    }
  },
  taskWorldUrls: {
    required: (isRequirementData.value?.taskType == 3 && isRequirementData.value?.isTs == 2) ? true : false,
    message: "必填",
    trigger: "blur"
  },
  // childCaseList: {
  //   required: isRequirementData.value == null ? false : isRequirementData.value.taskType == 3 ? true : false,
  //   message: "必填",
  //   trigger: "blur"
  // }
});
const testSuccessFormData = ref<any>({
  itemRequirementChildId: null,
  taskMsg: "",
  taskWorldUrls: [],
  filePath: "",
  childCaseList: [],
});
const requirementCaseList = ref<any>([]);// 该任务测试用例列表




// TODO 点击创建任务
// const createRequirementClick = () => {
//   router.push({
//     path: "/requirement/create",
//   });
// };

// TODO 开启添加Bug页面
const handleOpenAddBug = (id: number) => {
  isRequirementID.value = id;
  dialogAddBugVisible.value = true;
  // router.push({
  //   path: "/experiment/bugs",
  // });
};


// TODO 获取我所有的研发任务、分类并计数
const getAllRequirements = async () => {
  loading.value = true;
  userAuthId.value = localStorage.getItem("authorityId");
  isTestId.value = isUserAuthId(userAuthId.value);

  // const { data } = await postPVPRequirement({
  const { data } = await postNewPVPRequirement({
    projectTitle: searchFormData.value.projectTitle,
    userName: searchFormData.value.userName,
    beginTime: searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime: searchFormData.value.time === null ? null : searchFormData.value.time[1]
  });

  if (data.code === 200) {
    if (data.data === null) {
      allRequirements.value = [];
      loading.value = false;
      return;
    } else {
      allRequirements.value = data.data;

      if (allRequirements.value.length > 0) {
        // 1、将响应数据根据requirementFatherStatus进行分类并统计
        const statusCount = {} as any;

        allRequirements.value.forEach((item: any) => {
          let childStatus = item.requirementChildStatus;

          if (statusCount[childStatus]) {
            statusCount[childStatus].total++;
            // 判断该item是否已经添加
            if (!statusCount[childStatus].requirements.includes(item.ID)) {
              statusCount[childStatus].requirements.push(item);
            }
          } else {
            statusCount[childStatus] = {
              status: Number(childStatus),
              total: 1,
              requirements: [item]
            }
          }
        });

        allRequirements.value = Object.values(statusCount);

        // 动态添加样式
        const cardLayoutBox = document.getElementById("cardLayoutBox");
        let length = allRequirements.value.length;
        if (length % 3 == 0) {
          cardLayoutBox?.style.setProperty("justify-content", "space-between");
        } else {
          cardLayoutBox?.style.setProperty("justify-content", "flex-start");
        };
        loading.value = false;
      }
      loading.value = false;
    }
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    return;
  };

  loading.value = false;
};



// 查看需求
const handleRowClick = async (id: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};


// ! 操作
const handleCommand = async (val: any) => {
  isRequirementID.value = val.requirement.itemRequirementId;
  isRequirementData.value = val.requirement;

  switch (val.operate) {
    case 1:
      ElMessage.info("待开发");
      break;
    case 2:
      // ElMessage.info("开发中");
      // taskType:1
      if (isRequirementData.value.taskType == 1 || isRequirementData.value.taskType == 0) {
        dialogReviewMeetVisible.value = true;
      } else {
        // ElMessage.info("非上线任务-完成");
        dialogTaskResultVisible.value = true;
        initConfig.value = {
          tipText: "",
          type: "primary",
          plain: true,
          btnText: "上传",
          fileUrl: "/file/upload_file",
          fileType: "successFiles",
          fileTypeId: "5",
        }
      }
      break;
    case 3:
      // 根据itemRequirementWorldDetailed判断是否已经上传详细设计
      if (val.requirement.itemRequirementWorldDetailed == "") {
        // 若没有上传，则开启上传详细设计弹窗
        dialogDesignFileVisible.value = true;
      } else {
        // 若已上传，则先获取已分配的测试人员列表，并开启提测弹窗
        await handleGetJoinTests(isRequirementID.value);
        testFormData.value.childId = val.requirement.ID;
        if (isRequirementData.value.isGetTest == 1) {
          isChangeData.value = false;
        } else {
          isChangeData.value = true;
        }
        dialogTestVisible.value = true;
      }
      break;
    case 4:
      ElMessage.info("审核详细设计");
      break;
    case 5:
      // taskType:1
      if (isRequirementData.value.taskType == 1 || isRequirementData.value.taskType == 0) {
        //  测试操作
        // if (isTestId.value) {
        if (isRequirementData.value.isTs === 3) {
          // 判断是否上传测试用例
          if (isRequirementData.value.isUploadCase == 1) {
            // 未上传测试用例
            testCaseSearch.value = {
              itemItemId: isRequirementData.value.itemItemId,
              childId: isRequirementData.value.ID,
              isUploadCase: isRequirementData.value.isUploadCase,
              fatherId: isRequirementData.value.itemRequirementId
            };
            dialogTestCaseVisible.value = true;
          } else {
            // 已上传测试用例
            // if (isRequirementData.value.isGetTest == 2 && isRequirementData.value.requirementBossName !== '刘涛' && isRequirementData.value.requirementBossName !== '胡文斌') {
            await handleTestUserList(isRequirementID.value);
            await handleAllBugList(isRequirementID.value);
            dialogTestResultVisible.value = true;
            // } else {
            //   dialogTestResultVisible.value = true;
            // };
          }
        } else {
          //  研发操作
          // ElMessage.info("研发操作")
          await handleAgainTestList(isRequirementID.value);
          dialogAgainTestVisible.value = true;
        }
      } else {
        if (isRequirementData.value.isUploadCase == 1 && isRequirementData.value.taskType == 3) {
          // 未上传测试用例
          testCaseSearch.value = {
            itemItemId: isRequirementData.value.itemItemId,
            childId: isRequirementData.value.ID,
            isUploadCase: isRequirementData.value.isUploadCase,
            fatherId: isRequirementData.value.itemRequirementId
          };
          dialogTestCaseVisible.value = true;
        } else {
          // ElMessage.info("回归任务-已上传测试用例-测试完成");
          const { data } = await GetChildTestCaseList(isRequirementData.value.ID);
          if (data.code === 200) {
            requirementCaseList.value = data.data;
            loading.value = false;
          } else {
            ElMessage.error(data.msg);
            loading.value = false;
            throw console.error(data.msg);
          }
          dialogTaskResultVisible.value = true;
        }
      }
      break;
    case 6:
      // ElMessage.info("待上线评审");
      dialogTaskResultVisible.value = true;
      break;
    case 7:
      ElMessage.info("已上线");
      break;
    case 9:
      // 关闭childStatus，并刷新fatherStatus
      await updateChildStatus(isRequirementData.value, val.operate);
      break;
    default:
      // 关闭childStatus，并刷新fatherStatus
      await updateChildStatus(isRequirementData.value, val.operate);
      break;
  }
};

// TODO 待开发->开发中：需求评审会议纪要
const handleDeveloping = async () => {
  // 判断会议纪要是否为空
  if (reviewMeetingMsg.value.trim() == "") {
    ElMessage.warning("请填写需求评审会议纪要！");
    return;
  } else {
    // 提交会议纪要
    const { data } = await PutShowNeedTip({
      requirementChildId: isRequirementData.value.ID,
      itemRequirementNeedEasy: reviewMeetingMsg.value
    });
    if (data.code === 200) {
      ElMessage.success(data.msg);
      dialogReviewMeetVisible.value = false;
      loading.value = true;
      // 刷新fatherStatus
      await updateFatherStatus(isRequirementID.value);
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  }
};


// TODO 接收子组件中上传的文件地址
const handleUpdateFilePaths = (value: any) => {
  filePath.value = value;
};

// 上传文件后将文件与需求绑定
const handleDesignFile = async (id: number) => {
  dialogDesignFileVisible.value = true;
  if (filePath.value.length == 0 && newAssFilesList.value.length == 0) {
    ElMessage.warning("必须上传详细设计");
    return;
  } else {
    // 将文件地址用"|"拼接成字符串
    if (filePath.value.length > 0 && newAssFilesList.value.length > 0) {
      filePaths.value = filePath.value.map((item: any) => item).join('|') + '|' + newAssFilesList.value.join('|');
    } else {
      if (filePath.value.length === 0) {
        filePaths.value = newAssFilesList.value.join('|');
      } else {
        filePaths.value = filePath.value.map((item: any) => item).join('|');
      }
    };


    await handleUploadRequirement({
      itemRequirementId: id,
      fileType: 3,
      draftPath: null,
      summaryPath: null,
      detailedPath: filePaths.value,
      meetingPath: null,
      onLineMeetingPath: null
    }).then(async () => {
      await handleGetJoinTests(isRequirementID.value);
      testFormData.value.childId = id;
      dialogTestVisible.value = true;
      dialogDesignFileVisible.value = false;

      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    }).catch(() => {
      throw console.error();
    })
  }
};

// TODO 获取提测人员列表
const handleGetJoinTests = async (val: any) => {
  await GetJoinTests(val).then(async (res: any) => {
    if (res.data.data.length > 0) {
      testOptions.value = res.data.data;
      // testFormData.value.ts = testOptions.value.map((item: any) => item.uuid);
    } else {
      testOptions.value.length = 0;
    }
  }).catch((error) => {
    throw console.error(error);
  });
};


// TODO 开发中->点击【提测】->提测中
const submitTestData = async (formEl: FormInstance | undefined) => {

  if (!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;
    // 处理表单数据
    testFormData.value.ts = testOptions.value.filter((item: any) => testFormData.value.ts.includes(item.uuid)).map((item: any) => ({
      userName: item.nickName,
      uuid: item.uuid
    }));

    // 提交提测表单数据,并更新状态
    const { data } = await postSubmitTestRequirement(testFormData.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      dialogTestVisible.value = false;
      // await updateChildStatus(isRequirementData.value, isRequirementData.value.requirementChildStatus);
      formEl.resetFields();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    };
  } catch (error) {
    // loading.value = false;
    ElMessage.error("表单校验失败");
    throw console.error(error);
  }
};

// TODO 更新childStatus，fatherStatus状态
const updateChildStatus = async (val: any, status: number) => {
  loading.value = true;
  // 刷新fatherStatus
  await updateFatherStatus(val.itemRequirementId);
  await getAllRequirements();
  loading.value = false;
};

// TODO 关闭弹窗
const handleCloseDiglog = () => {
  // isRequirementData.value = null;

  // 清空会议评审纪要
  reviewMeetingMsg.value = "";
  dialogReviewMeetVisible.value = false;

  // 关闭上传详细设计弹窗
  fileText.value = [];
  filePath.value = [];
  resetFiles.value = false;
  setTimeout(() => {
    resetFiles.value = true;
  }, 100);
  dialogDesignFileVisible.value = false;


  // 查看需求弹窗
  clearData.value = true;

  newAssFilesList.value = [];
  filePaths.value = "";
};

// TODO 关闭提测分支弹窗
const handleCloseTestDialog = () => {
  // 关闭提测弹窗
  testFormData.value = {
    childId: null,
    ts: [],
    pullBranch1: "",
    pullBranch2: "",
    itemRequirementYTOYTip: "",
    itemRequirementYTOYNumber: 0
  };
  testFormRef.value?.resetFields();
  againTestFormRef.value?.resetFields();
  dialogTestVisible.value = false;
};
/* 测试中事件函数 */
// TODO 是否通过测试开关发生改变时触发事件
const handleChangeIsTestResult = async (val: number) => {
  if (val) {
    testFaliedBugForm.value = {
      childChildId: null,
      bugIds: []
    };
    testFaliedBugRef.value?.resetFields();
  } else {
    showTipCTOYForm.value = {
      childChildIdId: null,
      itemRequirementCTOYTip: "",
      itemRequirementCTOYNumber: 100,
      childId: null,
      testToTestBossTip: "",
      testToTestBossTipNumber: 100,
    };
    showTipCTOYRef.value?.resetFields();
  }
};

// TODO 关闭测试中操作弹窗
const handleCloseTestScoresDialog = () => {
  isTestResult.value = true;
  showTipCTOYForm.value = {
    childChildIdId: null,
    itemRequirementCTOYTip: "",
    itemRequirementCTOYNumber: 100,
    childId: null,
    testToTestBossTip: "",
    testToTestBossTipNumber: 100,
  };
  testFaliedBugForm.value = {
    childChildId: null,
    bugIds: []
  };
  testToTestFormData.value = {
    childId: null,
    testToTestBossTip: "",
    testToTestBossTipNumber: 100
  };

  testFaliedBugRef.value?.resetFields();
  showTipCTOYRef.value?.resetFields();
  testToTestFormRef.value?.resetFields();
  dialogTestResultVisible.value = false;
};

// TODO 测试负责人创建的需求-测试对测试负责人评价
const handleUpdateSubmitNotTip = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      testToTestFormData.value.childId = isRequirementData.value.ID;

      const { data } = await PutTestToBossTip(testToTestFormData.value);
      if (data.code === 200) {
        ElMessage.success(data.msg);
        // 提交测试通过
        const resData = await GetUpdateSubmitNotTips(isRequirementData.value.ID);
        if (resData.data.code === 200) {
          ElMessage.success(resData.data.msg);
          handleCloseTestScoresDialog();
          loading.value = true;
          await getAllRequirements();
          loading.value = false;
        } else {
          ElMessage.error(resData.data.msg);
          throw console.error(resData.data.msg);
        };
      } else {
        ElMessage.error(data.msg);
        throw console.error(data.msg);
      };
    } else {
      throw console.error(fields);
    }
  })
};

// TODO 测试通过，并对研发和测试负责人评论
const submitScoreData = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    showTipCTOYForm.value.childId = isRequirementData.value.ID;

    const { data } = await PutShowTipCTOY(showTipCTOYForm.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseTestScoresDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  } catch (error) {
    loading.value = false;
    throw console.error(error);
  }
};

// TODO 测试获取所有提测人员列表
const handleTestUserList = async (id: number) => {
  const { data } = await GetMySubmitByRequirementChild(id);
  if (data.code === 200) {
    allTestUserList.value = data.data;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 根据需求ID获取bug列表
const handleAllBugList = async (id: number) => {
  const { data } = await GetRequirementsBugs(id);
  if (data.code == 200) {
    if (data.data[0].requirementBugs.length !== 0) {
      allBugList.value = data.data[0].requirementBugs.map((item: any) => {
        return {
          key: item.ID,
          label: item.bug_title,
          disabled: (item.bug_status == 6 || item.bug_status == 7) ? true : false,
        }
      });

    } else {
      allBugList.value = [];
    }
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 添加Bug
const handleSubmitSuccess = async (success: boolean) => {
  if (success) {
    dialogAddBugVisible.value = false;
    submitLoading.value = true;
    await handleAllBugList(isRequirementID.value);
    submitLoading.value = false;
  } else {
    dialogAddBugVisible.value = false;
    return;
  };
};




// TODO 测试不通过
const handleTestFalied = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    const { data } = await PostSubmitTestStatus(testFaliedBugForm.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseTestScoresDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      return;
    }
  } catch (error) {
    throw console.error(error);
  }
};

// TODO 研发人员重新提测时获取测试名单
const handleAgainTestList = async (id: number) => {
  const { data } = await GetSubmitRequirementList(id);
  if (data.code === 200) {
    againTestOptions.value = data.data;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 关闭重新提测弹窗
const handleCloseAgainTestDialog = () => {
  againTestFormData.value = {
    childChildId: null,
    pullBranch1: "",
    pullBranch2: "",
    submitTest: "",
    ts: [{
      userName: "",
      uuid: ""
    }]
  };
  againTestOptions.value = [];
  againTestFormRef.value?.resetFields();
  dialogAgainTestVisible.value = false;
};

// TODO 提交重新提测表单数据
const submitAgainTestData = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    // 处理重新提测提交数据
    againTestFormData.value.ts[0].userName = againTestOptions.value.find((item: any) => item.ID == againTestFormData.value.childChildId).testName;
    againTestFormData.value.ts[0].uuid = againTestOptions.value.find((item: any) => item.ID == againTestFormData.value.childChildId).testUUID;

    const { data } = await PostSubmitTestRequirementTwo(againTestFormData.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseAgainTestDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;

    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    };
  } catch (error) {
    ElMessage.error("表单校验失败");
    throw console.error(error);
  }
};


// 刷新fatherStatus
const updateFatherStatus = async (id: number) => {
  const { data } = await getNewFatherRequirementStatus({
    requirementId: id
  });

  if (data.code !== 200) {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 导入测试用例监听
const handleAddSuccess = async (success: boolean) => {
  if (success) {
    dialogTestCaseVisible.value = false;
    // dialogTestResultVisible.value = true;
    loading.value = true;
    await updateFatherStatus(isRequirementID.value);
    await getAllRequirements();
    loading.value = false;
  } else {
    dialogTestCaseVisible.value = false;
    return;
  }
};


/** 任务完成 */

// 富文本数据更新
const updateMsg = (newValue: any) => {
  testSuccessFormData.value.taskMsg = newValue;
  return testSuccessFormData.value.testMsg;
};

// TODO 关闭任务完成弹窗
const handleCloseTestSuccessDialog = () => {
  testSuccessFormData.value.itemRequirementChildId = null;
  testSuccessFormData.value.taskMsg = "";
  testSuccessFormData.value.taskWorldUrls = [];
  testSuccessFormData.value.filePath = "";
  testSuccessFormData.value.childCaseList = [];
  requirementCaseList.value = [];

  fileText.value = [];
  filePath.value = [];
  newAssFilesList.value = [];

  resetFiles.value = true;
  setTimeout(() => {
    resetFiles.value = false;
  }, 100);

  testSuccessFormRef.value?.resetFields();
  dialogTaskResultVisible.value = false;
};

const selectable = (row: any) => ![0].includes(row.ID);
// TODO 多选任务中完成的测试用例
const handleSelectionChange = (val: any) => {
  testSuccessFormData.value.childCaseList = val.map(((item: any) => item.ID));
};

// TODO 确认任务完成，提交数据
const submitTestSuccessData = async (formEl: FormInstance | undefined) => {
  testSuccessFormData.value.itemRequirementChildId = isRequirementData.value.ID;

  let files = [];
  files = filePath.value.map((item: any) => item);
  files.unshift(...newAssFilesList.value.reverse());
  
  testSuccessFormData.value.taskWorldUrls = files;

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const { data } = await TaskRequirementSuccess(testSuccessFormData.value);
      if (data.code == 200) {
        handleCloseTestSuccessDialog();
        await getAllRequirements();
      } else {
        ElMessage.error(data.msg);
        throw console.error(data.msg);
      }

    } else {
      ElMessage.error("表单校验失败！");
      throw console.error("表单校验失败！");
    }
  })
};

// TODO　关联文件
// 监听子组件的事件函数，并接收子组件中选中的文件
const handleAddFiles = (data: any) => {
  newAssFilesList.value = newAssFilesList.value.concat(data);
};
// 删除关联文件
const handleDelAssFile = (row: any) => {
  newAssFilesList.value.splice(newAssFilesList.value.indexOf(row), 1);
};


onMounted(async () => {
  await getAllRequirements();

});
</script>

<style lang="scss" scoped>
.content-container {
  min-width: 1160px;
  height: 100%;
  display: flex;
  overflow-x: auto;
  flex-direction: column;

  // TODO 搜索区域
  /* 滚动条整体样式 */
  .search-wrap {
    width: 100%;
    //height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-start;

    .search-wrap-item {
      margin-right: 10px;
      margin-bottom: 0;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  }

  // 需求列表区域
  .card-layout-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;
    //flex-wrap: wrap;  换行布局
    overflow-y: auto;

    // 无数据时显示
    .card-not-requirement {
      color: #909399;
      margin: auto;
    }

    .card-box {
      //width: 32.6%;
      min-width: 380px;
      max-width: 440px;
      //height: 360px;
      height: 97%;
      border: 1px solid #d0d0d0;
      border-radius: 6px;
      margin: 0 0.3% 1% 0.3%;
      display: flex;
      flex-direction: column;
      background: #fff;

      // 列表标题
      .card-header-box {
        width: 100%;
        height: 40px;
        padding: 0 10px;
        line-height: 40px;
        font-size: 14px;
        font-family: Helvetica, Arial, sans-serif;
        //color: white;
        border-radius: 6px 6px 0 0;
        border-bottom: 1px solid #dbdfe0;
        color: #bac0cb;

        span {
          color: #fff;
          font-size: 14px;
        }
      }

      // 列表盒子
      .card-list-box {
        width: 100%;
        // height: calc(100% - 40px);
        display: flex;
        justify-content: flex-start;
        overflow-y: auto;

        .card-list {
          width: 100%;
          height: 100%;
          font-size: 14px;

          .card-list-item {
            width: 100%;
            min-height: 71px;
            //height: 70px;
            padding: 5px 10px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            position: relative;

            // 操作
            .operate-box {
              width: 20px;
              height: 100%;
              display: flex;
              align-items: center;

            }

            //
            .card-list-left {
              width: calc(100% - 20px);
              display: flex;
              flex-direction: column;
              flex-wrap: nowrap;
              position: relative;

              .icon-img {
                position: absolute;
                right: -25px;
                bottom: 0;
              }

              //需求类别
              .card-list-type {
                height: 20px;
                margin-bottom: 5px;

                img {
                  float: left;
                  padding-right: 5px;
                }

                span {
                  float: left;
                  display: inline-block;
                  height: 20px;
                  margin-right: 5px;
                }
              }

              // 需求标题
              .card-header-title-box {
                width: 100%;
                cursor: pointer;
                font-size: 15px;

                .el-text {
                  width: 100%;
                }

                .el-text:hover {
                  color: #409EFF;
                }
              }

              // 附加信息样式
              .card-list {
                width: 100%;
                display: flex;
                justify-content: space-between;
                flex-direction: row;
                white-space: nowrap;
                padding: 0;
                font-size: 0.7rem;
                color: #999;

                .card-list-small-item {
                  margin: 0 10px 0 0;
                }

                .item-status {
                  width: 120px;
                }

                .boss-name {
                  width: 110px;
                  font-size: 12px;
                }

                .test-list {
                  width: 180px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  font-size: 12px;
                }

                .begin-time {
                  width: 110px;
                  font-size: 12px;
                  position: relative;
                }

                .operate-box {
                  width: 20px;
                  text-align: right;
                }
              }
            }
          }
        }
      }
    }

    /* 当屏幕宽度超过 1620px 时，调整 .card-box 的宽度 */
    @media (min-width: 1921px) {
      .card-box {
        width: 24.2%;
        /* 新的宽度 */
      }
    }

    /* 当屏幕宽度超过 2680px 时，调整 .card-box 的宽度 */
    @media (min-width: 2681px) {
      .card-box {
        width: 19.32%;
        /* 新的宽度 */
      }
    }

    .card-header-title-box:hover {
      color: #409EFF;
    }

    .card-list-item:hover {
      background-color: rgb(216.8, 235.6, 255);
    }
  }

  // 审核需求
  .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;

    p {
      margin-right: 20px;
    }
  }

  // 需求草稿
  .info-file-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    margin: 10px 0 0;

    .info-content-title {
      width: 100px;
      padding: 0 10px;
    }

    .info-file-ul {
      width: calc(100% - 70px);
      text-align: left;
      display: flex;
      flex-direction: row;

      .info-file-item {
        width: 60px;
        margin-right: 10px;
      }

      .info-file-item:hover {
        color: #409EFF;
        cursor: pointer;
      }
    }
  }

  // TODO 分配需求弹窗
  .dialog-container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .dialog-form-title {
      font-weight: bold;
      padding: 10px;
      margin-bottom: 20px;
      background-color: #f0f0f0;
    }

    .dialog-form-box {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-bottom: 30px;

      .el-form-item {
        margin: 0 10px 0 0;
      }
    }

    .dialog-footer {
      width: 100%;
      text-align: right;
    }

    // 提测分支表单样式
    .dialog-test-form {
      max-height: 610px;
      overflow-y: auto;
      padding: 20px 20px 0 20px;

      .dialog-footer {
        text-align: right;
      }
    }

    // 上传测试用例样式
    .upload-case {
      margin-left: 20px;
    }
  }

  .dialog-form-footer {
    width: 100%;
    text-align: right;
  }

  .cell-item {
    display: flex;
    align-items: left;
  }

  .margin-top {
    padding: 10px 20px;
  }

  .red-text {
    color: red;
  }

  .red-bj {
    background-color: #fff1f0;
  }

  .card-finished {
    color: #999;
    text-decoration: line-through;
  }
}
</style>
